@echo off
setlocal enabledelayedexpansion
chcp 65001 > nul

REM ==== 设置安全路径 ====
set "SAFE_PATH=%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;"
set "PATH=%SAFE_PATH%"

REM ==== 强制刷新环境变量 ====
echo [INFO] 强制刷新环境变量...
call "%cd%\refresh_env.cmd"

REM ==== 设置路径 ====
set "SERVICE_DIR=%~dp0"
set "SERVICE_EXE=%SERVICE_DIR%ScanOSService.exe"
set "SERVICE_XML=%SERVICE_DIR%ScanOSService.xml"
set "LOG_FILE=%SERVICE_DIR%service-install.log"

REM ==== 验证文件存在 ====
if not exist "%SERVICE_EXE%" (
    echo [ERROR] 未找到 ScanOSService.exe
    echo 路径: %SERVICE_EXE%
    exit /b 1
)

REM ==== 停止服务 ====
echo [INFO] 停止服务...
net stop ScanOSService >nul 2>&1
sc stop ScanOSService >nul 2>&1
taskkill /f /im ScanOSService.exe >nul 2>&1

REM ==== 卸载服务 ====
echo [INFO] 卸载服务...
if exist "%SERVICE_EXE%" (
    "%SERVICE_EXE%" uninstall >nul 2>&1
)
sc delete ScanOSService >nul 2>&1

REM ==== 生成配置文件 ====
echo [INFO] 生成服务配置文件...
set "JAVA_HOME="

REM 1. 尝试注册表路径
for /f "tokens=2,*" %%a in ('reg query "HKLM\SOFTWARE\ScanOS" /v JavaHome 2^>nul') do set "JAVA_HOME=%%b"

REM 2. 尝试标准JDK注册表
if not defined JAVA_HOME (
    for /f "tokens=2,*" %%a in ('reg query "HKLM\SOFTWARE\JavaSoft\Java Development Kit\17" /v JavaHome 2^>nul') do set "JAVA_HOME=%%b"
)

REM 3. 尝试默认路径
if not defined JAVA_HOME (
    if exist "C:\Program Files\Eclipse Adoptium\jdk-17.0.14.7-hotspot" (
        set "JAVA_HOME=C:\Program Files\Eclipse Adoptium\jdk-17.0.14.7-hotspot"
    ) else if exist "C:\Program Files\Java\jdk-17" (
        set "JAVA_HOME=C:\Program Files\Java\jdk-17"
    )
)

if not defined JAVA_HOME (
    echo [ERROR] 无法确定JAVA_HOME
    exit /b 1
)

(
  echo ^<?xml version="1.0" encoding="UTF-8"?^>
  echo ^<service^>
  echo   ^<id^>ScanOSService^</id^>
  echo   ^<name^>ScanOS Service^</name^>
  echo   ^<description^>ScanOS Background Service^</description^>
  echo   ^<executable^>cmd^</executable^>
  echo   ^<arguments^>/c ""%~dp0start-lib-app-server.bat""^</arguments^>
  echo   ^<workingdirectory^>%~dp0^</workingdirectory^>
  echo   ^<logpath^>%~dp0Logs^</logpath^>
  echo   ^<logmode^>rotate^</logmode^>
  echo   ^<onfailure action="restart" delay="10 sec"/^>
  echo   ^<startmode^>Automatic^</startmode^>
  echo   ^<env name="PATH" value="%%PATH%%;%JAVA_HOME%\bin" /^>
  echo   ^<env name="JAVA_HOME" value="%JAVA_HOME%" /^>
  echo ^</service^>
) > "%SERVICE_XML%"

REM ==== 安装服务 ====
echo [INFO] 安装服务...
"%SERVICE_EXE%" install
if %errorlevel% neq 0 (
    echo [ERROR] 主安装方法失败，错误代码: %errorlevel%
    
    REM 尝试备选方案
    echo [INFO] 尝试备选安装方法...
    sc create ScanOSService binPath= "\""%SERVICE_EXE%\"" run" start= auto DisplayName= "ScanOS Service"
    if %errorlevel% neq 0 (
        echo [ERROR] 备选安装方法失败，错误代码: %errorlevel%
        exit /b %errorlevel%
    )
)

REM ==== 启动服务 ====
echo [INFO] 启动服务...
net start ScanOSService
if %errorlevel% neq 0 (
    echo [ERROR] 服务启动失败
    exit /b 1
)

echo [SUCCESS] 服务安装完成
exit /b 0